/*
 * @Description  : 改用signalr
 * @Author       : zhao
 * @Date         : 2023-01-29 11:04:49
 * @LastEditors  : zhao
 * @LastEditTime : 2023-01-29 14:26:29
 */
import { defineStore } from 'pinia';

import { WebsocketStates } from './interface';
import { CSGetBorrowingForm } from '/@/api/userInfo.js';
import { ElMessage } from 'element-plus';

import * as signalR from "@microsoft/signalr";
export const useWebsocket = defineStore('websocket', {
    state: (): WebsocketStates => ({
        websocket: null,
        isConnect: false,
        rec: null,// 断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码,
        wsUrl: 'ws://http://175.188.189.182:10081/GeoArcShareInterface/api/SignalR/CSGetBorrowingForm' // websocket 默认连接地址
    }),
    actions: {

        //实时通信
        creatWebSocket() {
            if ("WebSocket" in window) {
                console.log("当前浏览器 windows");
            } else if ("MozWebSocket" in window) {
                console.log("当前浏览器 windows");
            } else {
                console.log("当前浏览器 Not support websocket");
            }

            try {
                this.initWebSocket(); // 初始化websocket连接
            } catch (e) {

                this.reConnect(); // 如果无法连接上 webSocket 那么重新连接！可能会因为服务器重新部署，或者短暂断网等导致无法创建连接
            }

        },

        initWebSocket() {
            this.websocket = new signalR.HubConnectionBuilder().withAutomaticReconnect().withUrl(this.wsUrl).build();

            this.websocket.onopen = function (e: any) {
                this.websocketOpen(e);
            };

            // 接收
            this.websocket.onmessage = function (e: any) {
                this.websocketonmessage(e);
            };

            // 连接发生错误
            this.websocket.onerror = function () {
                console.log("WebSocket连接发生错误");
                this.isConnect = false; // 连接断开修改标识
                this.reConnect(); // 连接错误 需要重连
            };

            this.websocket.onclose = function (e: any) {
                this.websocketclose(e);
            };

        },

        reConnect() {
            if (this.isConnect) return; // 如果已经连上就不在重连了
            this.rec && clearTimeout(this.rec);
            this.rec = setTimeout(() => {
                // 延迟5秒重连  避免过多次过频繁请求重连
                this.creatWebSocket();
            }, 5000);

        },
        // 创建连接
        websocketOpen() {

        },
        // 数据接收
        websocketonmessage(e: any) {
            console.log("数据接收", e.data);

            // let data = JSON.parse(decodeUnicode(e.data))
        },
        // 关闭
        websocketclose(e: any) {
            console.log(e);
            this.isConnect = false; // 断开后修改标识
            console.log("connection closed (" + e.code + ")");
        },

        // 数据发送
        websocketsend(data: any) {
            console.log("发送的数据", data, JSON.stringify(data));
            this.websocket.send(JSON.stringify(data));
        },

        // 实际调用的方法==============

        // 发送
        sendWebSocket(data: any) {
            if (this.websocket.readyState === this.websocket.OPEN) { // 开启状态
                this.websocketsend(data);
            } else { // 若 未开启 / 正在开启 状态 ，则等待1s后重新调用
                setTimeout(() => {
                    this.sendWebSocket(data);
                }, 1000);
            }
        },

        // 关闭
        closeWebSocket() {
            this.websocket.close();
        }

    },
});